package com.sq.partner.manager.sso.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.GatewayCache;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.util.LogUtil;

/**
 * 本地登陆验证
 */
public class ManagerLoginFilter implements Filter {
	private static Logger logger = LogUtil.getLog(ManagerLoginFilter.class);
	private  List<Pattern> noCheckPatterns = new ArrayList<Pattern>();

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		boolean checkPass = checkLogin(req);
		if(checkPass){
			chain.doFilter(request, response);
		}else{
			String msg = "未登录或登录已过期，请重新登录";
			SSOFilter.doLoginError(req, res, msg);
		}
	}
	/**
	 * 验证是否登陆成功
	 */
	private static boolean checkLogin(HttpServletRequest request){
		boolean checkPass = false;
		HttpSession session = request.getSession(false);
		Object userObj = null;
		String userName = null;
		if(session != null ){
			String switchValue = GatewayCache.getCache(Constants.LOGIN_SWITCH_VALUE);
			userObj = session.getAttribute(Constants.SESSION_USER);
			if(userObj != null && userObj instanceof GatewayUser){
				GatewayUser user = (GatewayUser)userObj;
				if(user.getSwitchValue().equals(switchValue)){
					checkPass = true;
					userName = user.getUserName();
				}
			}
		}
		
		return checkPass;
	}
	

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}
}
